import React, { useState } from 'react';
import { useRequest, useDebounceFn } from 'ahooks';
import { apiGetArticleCategories, apiGetArticles } from '@/api/article.api';
import {
  Card,
  Form,
  Input,
  Table,
  Button,
  TreeSelect,
  Row,
  Col,
  Modal,
  message,
} from 'antd';
import { ColumnsType } from 'antd/es/table';
import { history, useModel } from 'umi';
import style from './index.module.less';
import { Category } from '@/pages/article/category';
import { ke } from '@/plugins/ke';
import useKTable from '@/hooks/useKTable';
import { useUrlState } from '@/plugins/hooks';

export default () => {
  const [query, setQuery] = useUrlState();

  let formId: number | null = Number(query?.id);
  if (isNaN(formId)) {
    formId = null;
  }
  const [form] = Form.useForm();
  const [modal, contextHolder] = Modal.useModal();

  // 分类树形数据
  const { data: categoies } = useModel('category');

  const [editId, setEditId] = useState<null | number>(formId);

  const { props, search, action } = useKTable(apiGetArticles, {
    form,
    onSuccess: () => {
      scrollTo(0, 0);
    },
  });

  // 延时搜索
  const { run: delaySearch } = useDebounceFn(
    e => {
      form.setFieldsValue(e);
      search.submit();
    },
    { wait: 500 },
  );

  // 点击处理
  const redirectEdit = (id: null | number) => {
    history.push({
      pathname: '/article/edit',
      query: {
        id: `${id}`,
      },
    });
  };

  // 删除
  const onDeleteRow = (result: any) => {
    modal.confirm({
      content: '确认删除吗?',
      onOk: () => {
        const hide = message.loading('删除中...', 0);

        setTimeout(() => {
          hide();
          setTimeout(() => message.success('删除成功'), 300);
        }, 2500);
      },
    });
  };

  // 更新表行
  const onUpdateRow = async (result: any) => {
    // const list = tableProps.dataSource;
    // const idx = list.findIndex(_ => _.id === result.data.id);
    // if (idx > -1) {
    //   list.splice(idx, 1, {
    //     ...list[idx],
    //     title: 'test'
    //   });
    //   console.log('res', list);
    // }
  };

  // 表列
  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id' },
    { title: '分类', dataIndex: 'cate_name', width: 120 },
    {
      title: '标题',
      render: row => {
        return (
          <div className={'text-overflow'} style={{ width: 200 }}>
            {row.title}
          </div>
        );
      },
    },
    { title: '点击量', dataIndex: 'view_count' },
    { title: '发布时间', dataIndex: 'create_time', width: 160 },
    {
      title: '操作',
      width: 200,
      align: 'center',
      render: row => {
        return (
          <div className={'k-btn-group'}>
            <Button size={'small'} onClick={() => redirectEdit(row.id)}>
              编辑
            </Button>
            <Button size={'small'} onClick={() => onDeleteRow(row)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      {contextHolder}

      <div style={{ display: editId === null ? 'block' : 'none' }}>
        <div style={{ marginBottom: 20 }}>
          <Button type={'primary'} onClick={() => redirectEdit(0)}>
            发布新文章
          </Button>
        </div>

        <Card style={{ marginBottom: 20 }} className={'search'}>
          <Form form={form}>
            <Row justify={'end'}>
              <Col span={6}>
                <Form.Item name={'cate_id'} className={style.formItem}>
                  <TreeSelect
                    placeholder={'选择分类'}
                    treeData={categoies}
                    allowClear={true}
                    multiple={true}
                    onChange={search.submit}
                  />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item name={'keyword'} className={style.formItem}>
                  <Input
                    placeholder={'输入文章标题搜索'}
                    allowClear={true}
                    onChange={e =>
                      delaySearch({
                        field: 'keyword',
                        value: e.target.value,
                      })
                    }
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card>
          <Table rowKey={'id'} columns={columns} {...props} />
        </Card>
      </div>
    </div>
  );
};
